package com.zoro.barn.business.service.system.business.rolemenu.service;

import com.zoro.barn.business.service.system.business.menu.entiity.BarnMenu;
import com.zoro.barn.business.service.system.business.rolemenu.dao.BarnRoleMenuMapper;
import com.zoro.barn.business.service.system.business.rolemenu.entity.BarnRoleMenu;
import com.zoro.barn.business.service.system.exceptions.DataLostException;
import com.zoro.barn.business.service.system.exceptions.DataUncompletedException;
import com.zoro.barn.business.service.system.business.menu.dao.BarnMenuMapper;
import com.zoro.barn.commons.tools.string.IDs;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;

/**
 * @author zhaoxingwu
 */
@Service
public class BarnRoleMenuService {

    @Resource
    private BarnRoleMenuMapper barnRoleMenuMapper;
    @Resource
    private BarnMenuMapper menuMapper;


    /**
     * add relationship between one role and one menu
     *
     * @param roleId role
     * @param menuId menu
     */
    @Transactional(rollbackFor = Exception.class)
    public void add(String roleId, String menuId) {

        if (StringUtils.isAnyBlank(roleId, menuId)) {
            throw new DataUncompletedException();
        }

        int c = this.barnRoleMenuMapper.hasRoleMenu(roleId, menuId);
        if (c > 0) {
            return;
        }
        BarnRoleMenu roleMenu = new BarnRoleMenu();
        roleMenu.setPid(IDs.uuid());
        roleMenu.setMenuId(menuId);
        roleMenu.setRoleId(roleId);

        this.barnRoleMenuMapper.insert(roleMenu);

        // 如果有父级，父级也要一并加进去
        BarnMenu menu = this.menuMapper.getById(menuId);
        if (menu == null) {
            throw new DataLostException();
        }
        if (StringUtils.isNotBlank(menu.getParentId())) {
            int cp = this.barnRoleMenuMapper.hasRoleMenu(roleId, menu.getParentId());
            if (cp > 0) {
                return;
            }
            BarnRoleMenu parent = new BarnRoleMenu();
            parent.setPid(IDs.uuid());
            parent.setMenuId(menu.getParentId());
            parent.setRoleId(roleId);

            this.barnRoleMenuMapper.insert(parent);
        }

    }

    /**
     * delete relationship between one role and one menu
     *
     * @param roleId role
     * @param menuId menu
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(String roleId, String menuId) {
        if (StringUtils.isAnyBlank(roleId, menuId)) {
            return;
        }
        BarnRoleMenu roleMenu = new BarnRoleMenu();
        roleMenu.setMenuId(menuId);
        roleMenu.setRoleId(roleId);
        this.barnRoleMenuMapper.delete(roleMenu);
        // 删除所有子节点
        this.barnRoleMenuMapper.deleteByParentId(roleId, menuId);
    }
}
